using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using StockExchanger.Helpers;
using StockExchanger.Models;

namespace StockExchanger.Controllers
{

    //
    // ViewModel Classes
    public class BuySellFormViewModel
    {

        // Properties
        public BuySell BuySell { get; private set; }
//        public SelectList Countries { get; private set; }

        // Constructor
        public BuySellFormViewModel(BuySell buysell)
        {
            BuySell = buysell;
//            Countries = new SelectList(PhoneValidator.Countries, Dinner.Country);
        }
    }
/*
    public class DseFormViewModel {

        // Properties
        public Dse     Dse    { get; private set; }
        public SelectList Countries { get; private set; }

        // Constructor
        public DseFormViewModel(Dse Dse) {
//            Dse = Dse;
            Countries = new SelectList(PhoneValidator.Countries, Dse.Country);
        }
    }
*/
    //
    // Controller Class

    [HandleError]
    public class StockController : Controller {

        private IBuySellRepository _repository;

        /// <summary>
        /// /////////////////////////////////////////////////////
        /// </summary>
        /// <returns></returns>


//        private ASPNETDBEntities _entities;

        //_entities.BuySell.ToList()
        // GET: /Home/


        [Authorize]
        public ActionResult Ledger()
        {

            //aspnet_User user = _repository.GetUser(User.Identity.Name);

/*            var dataContext = new StockBuySellDataContext();
            var user = from m in dataContext.aspnet_Users
                       select m;
            return View(user.ToList());
*/
            return View(_repository.ListAll());
        }

        [Authorize]
        public ActionResult Profile()
        {

            //            aspnet_User user = _repository.GetUser(User.Identity.Name);

            var dataContext = new StockBuySellDataContext();
            var user = from m in dataContext.aspnet_Users
                         select m;
            return View(user.ToList());


            /*            BuySell buysell = new BuySell()
                        {
                            StartDate = DateTime.Now
                        };
            */
 //           return View(_repository.ListAll());
        }

        public ActionResult ShareList()
               {
/*                    ViewData.Model = _entities.BuySell.ToList();
                 // ViewData.Model += _entities.BuySell.ToList();

                    return View();
*/
//                    var dataContext = new StockBuySellDataContext();
  //                  var buysells = from m in dataContext.BuySells
    //                             select m;
      //              return View(buysells);
                    return View(_repository.ListAll());


               }


        [Authorize]
        public ActionResult Buy(int id)
        {
            BuySell buySell = _repository.GetBuySell(id);
            if (buySell == null)
                return View("NotFound");

            buySell.EndDate = DateTime.Now;
            buySell.BoughtBy = User.Identity.Name;
            buySell.Sold = true;

            aspnet_User buyer = _repository.GetUser(buySell.BoughtBy);
            aspnet_User seller = _repository.GetUser(buySell.ListedBy);

            buyer.balance -= buySell.Quantity * buySell.Rate;
            seller.balance += buySell.Quantity * buySell.Rate;

            _repository.Save();
//            DataSource.DataContext.SubmitChanges();
/*            BuySell buysell = new BuySell()
            {
                StartDate = DateTime.Now
            };

            return View(new BuySellFormViewModel(buysell));
*/
            return RedirectToAction("ShareList");
        }


        
//        [AcceptVerbs("GET")]
        [Authorize]
        public ActionResult Sell()
        {

            BuySell buysell = new BuySell()
            {
                StartDate = DateTime.Now
            };

            return View(new BuySellFormViewModel(buysell));
        }


        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Sell(BuySell buySell)
        {

//            if (ModelState.IsValid)
  //          {

//                try
  //              {
                    buySell.ListedBy = User.Identity.Name;

//                    RSVP rsvp = new RSVP();
  //                  rsvp.AttendeeName = User.Identity.Name;
    //                dinner.RSVPs.Add(rsvp);

                    _repository.Add(buySell);
                    _repository.Save();

                    return RedirectToAction("ShareList");
//                    return RedirectToAction("Details", new { id = buySell.BuySellId });
    //            }
      //          catch
        //        {
//                    ModelState.AddModelErrors(buySell.GetRuleViolations());
          //      }
            //}

//            return View(new BuySellFormViewModel(buySell));
        }





/*
        
//        [ValidateAntiForgeryToken]
//        [AcceptVerbs("POST")]
        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Sell(FormCollection form)
        {
            BuySell BuySell = new BuySell();

//            try
  //          {
            this.UpdateModel(BuySell, new[] { "Id", "SellerID", "Item", "Quantity", "Rate", "StartDate", "BuyerId", "EndDate", "Sold", "Description" });
                _repository.Add(BuySell);

                return RedirectToAction("ShareList");

//                return RedirectToAction("Details", new { licensePlate = car.LicensePlate });
    //        }
      //      catch (RuleViolationException)
        //    {
          //      this.UpdateModelStateWithViolations(car, ViewData.ModelState);


            //    return View("New", car);
            //}
        }

*/


/*
        //[Bind(Exclude = "Id")]
        // POST: /Home/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Sell(BuySell itemToSell)
        {
            try
            {
                // TODO: Add insert logic here
//                _entities.AddToBuySell(itemToSell);
//                _entities.SaveChanges();

                return RedirectToAction("ShareList");
          }
            catch
            {
                return View();
            }
        }



        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Sell(FormCollection form)
        {
            var movieToAdd = new seller();

            // Deserialize (Include white list!)
            TryUpdateModel(movieToAdd, new string[] { "id", "companyname", "quantity", "rate", "date" }, form.ToValueProvider());

            // Validate
            if (String.IsNullOrEmpty(movieToAdd.Title))
                ModelState.AddModelError("Title", "Title is required!");
            if (String.IsNullOrEmpty(movieToAdd.Director))
                ModelState.AddModelError("Director", "Director is required!");

            // If valid, save movie to database
            if (ModelState.IsValid)
            {
                _entities.AddToseller(movieToAdd);
                _entities.SaveChanges();
                return RedirectToAction("ShareList");
            }

            // Otherwise, reshow form
            return View(movieToAdd);
        }
*/


        /// <summary>
        /// ////////////////////////////////////////////////////////////
        /// </summary>



//        IDseRepository DseRepository;

        //
        // Dependency Injection enabled constructors

        public StockController()
            : this(new BuySellRepository()) {
 //               _entities = new ASPNETDBEntities();
        }

        public StockController(IBuySellRepository repository) {
            _repository = repository;
        }

        //
        // GET: /Stock/
        //      /Stock/Page/2
/*
        public ActionResult Index(int? page) {

            const int pageSize = 10;

            var upcomingStock = DseRepository.FindUpcomingStock();
            var paginatedStock = new PaginatedList<Dse>(upcomingStock, page ?? 0, pageSize);

            return View(paginatedStock);
        }
*/
        //
        // GET: /Stock/Details/5

        public ActionResult Details(int id) {

            BuySell buySell = _repository.GetBuySell(id);

            if (buySell == null)
                return View("NotFound");

            if (buySell.Sold == true)
                return View("SorrySold");


            return View(buySell);
        }

        //
        // GET: /Stock/Edit/5

        [Authorize]
        public ActionResult Edit(int id) {

            BuySell buySell = _repository.GetBuySell(id);


            if (buySell.ListedBy != User.Identity.Name)
                return View("InvalidOwner");
//            if (!Dse.IsHostedBy(User.Identity.Name))
//                return View("InvalidOwner");

            return View(new BuySellFormViewModel(buySell));
        }

        //
        // POST: /Stock/Edit/5

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Edit(int id, FormCollection collection) {

            BuySell buySell = _repository.GetBuySell(id);

            if (buySell.ListedBy != User.Identity.Name)
                return View("InvalidOwner");

            try {
                UpdateModel(buySell);

                _repository.Save();

                return RedirectToAction("Details", new { id=buySell.BuySellId });
            }
            catch {
//                ModelState.AddModelErrors(Dse.GetRuleViolations());

                return View(new BuySellFormViewModel(buySell));
            }
        }

        //
        // GET: /Stock/Create
/*
        [Authorize]
        public ActionResult Create() {

            Dse Dse = new Dse() {
                EventDate = DateTime.Now.AddDays(7)
            };

            return View(new DseFormViewModel(Dse));
        } 

        //
        // POST: /Stock/Create

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Create(Dse Dse) {

            if (ModelState.IsValid) {

                try {
                    Dse.HostedBy = User.Identity.Name;

                    RSVP rsvp = new RSVP();
                    rsvp.AttendeeName = User.Identity.Name;
                    Dse.RSVPs.Add(rsvp);

                    DseRepository.Add(Dse);
                    DseRepository.Save();

                    return RedirectToAction("Details", new { id=Dse.DseID });
                }
                catch {
                    ModelState.AddModelErrors(Dse.GetRuleViolations());
                }
            }

            return View(new DseFormViewModel(Dse));
        }
*/

        //
        // HTTP GET: /Stock/Delete/1

        [Authorize]
        public ActionResult Delete(int id) {

            BuySell buySell = _repository.GetBuySell(id);

            if (buySell == null)
                return View("NotFound");

            if (buySell.ListedBy != User.Identity.Name)
                return View("InvalidOwner");

            if (buySell.Sold == true)
                return View("SorrySold");

            return View(buySell);
        }

        // 
        // HTTP POST: /Stock/Delete/1

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Delete(int id, string confirmButton) {

 /*           Dse Dse = DseRepository.GetDse(id);

            if (Dse == null)
                return View("NotFound");

            if (!Dse.IsHostedBy(User.Identity.Name))
                return View("InvalidOwner");
*/
            BuySell buySell = _repository.GetBuySell(id);

            if (buySell == null)
                return View("NotFound");

            if (buySell.ListedBy != User.Identity.Name)
                return View("InvalidOwner");

            if (buySell.Sold == true)
                return View("SorrySold");

            _repository.Delete(buySell);
            _repository.Save();

            return View("Deleted");
        }
    }
}
